package cn.jtfadmin.core.modules.sys.service.impl;

import cn.jtfadmin.base.lang.common.event.EntityEvent;
import cn.jtfadmin.base.lang.enums.EntityEventEnum;
import cn.jtfadmin.core.modules.sys.service.EntityLastDateTimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import javax.cache.CacheManager;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 *
 */
@Service
public class EntityLastDateTimeServiceImpl implements EntityLastDateTimeService, ApplicationListener<EntityEvent> {

    @Autowired
    protected CacheManager cacheManager;


    private String cacheName = "EntityLastDateTime";

    @Override
    public Optional<LocalDateTime> lastDateTime(Class<?> entityClass) {
        return Optional.ofNullable((LocalDateTime) cacheManager.getCache(cacheName).get(entityClass.getName()));
    }

    @Override
    public void onApplicationEvent(EntityEvent event) {
        if( event.getType().equals(EntityEventEnum.PRE_REMOVE)
                ||  event.getType().equals(EntityEventEnum.PRE_UPDATE)

        ){
            cacheManager.getCache(cacheName).put(event.getEntity().getClass().getName(), LocalDateTime.now());
        }
    }
}
